package belf.migrate.engine.admin.handler;

import belf.migrate.engine.BelfEvn;
import belf.migrate.engine.SubmitJob;
import belf.migrate.api.job.Job;
import belf.migrate.engine.job.JobResult;
import belf.migrate.engine.job.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import spark.Request;
import spark.Response;

import java.text.SimpleDateFormat;

import static belf.migrate.api.job.JobCode.SUCCESS;
import static spark.Spark.get;
import static spark.Spark.post;

/**
 * 提供与job调度相关的HTTP交互处理，包括调度Job，查看执行中
 */
@Slf4j
public class JobHandler {
    // 创建Gson对象
    private static Gson gson = new Gson();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void setupRoutes() {
        post("/submit", (request, response) -> { //提交一个可执行的Job，需要包含Job、Task、TaskConf三类信息
            return processSubmit(request, response);
        }, gson::toJson);

        post("/stop", (request, response) -> { //提交一个可执行的Job，需要包含Job、Task、TaskConf三类信息
            return stopJob(request, response);
        }, gson::toJson);

        post("/list", (request, response) -> {
            return listJob(request, response);
        }, gson::toJson);
    }

    private static JsonObject processSubmit(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        // 获取请求体中的JSON数据并反序列化为Job对象
        ObjectMapper mapper = new ObjectMapper();
        JsonObject jsonResponse = new JsonObject();
        try {
            Job job = mapper.readValue(request.body(), Job.class);
            jsonResponse = new SubmitJob().submitJob(job);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            jsonResponse.addProperty("code", 11);
            jsonResponse.addProperty("message", "解析请求的json格式失败");
        }

        // 返回JSON结果
        return jsonResponse;
    }

    private static Result<JsonArray> listJob(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        JsonArray jsonArray = new JsonArray();

        BelfEvn.getInstance().getJobs().forEach(job -> {
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("job_id", job.getJobId());
            jsonResponse.addProperty("job_mode", job.getTask().getJobMode().getName());
            jsonResponse.addProperty("task_type", job.getTask().getTaskType().getDesc());
            jsonResponse.addProperty("task_name", job.getTask().getName());
            jsonResponse.addProperty("task_desc", job.getTask().getDesc());
            jsonResponse.addProperty("task_id", job.getTask().getTaskId());
            if (job.getEndTime() != null) {
                jsonResponse.addProperty("start_time", sdf.format(job.getStartTime()));
            }
            if (job.getEndTime() != null) {
                jsonResponse.addProperty("end_time", sdf.format(job.getEndTime()));
            }
            if (job.getMissions() != null && !(job.getMissions().isEmpty())) {
                jsonResponse.addProperty("missions", gson.toJson(job.getMissions()));
            }
            jsonArray.add(jsonResponse);
        });


        return Result.success(jsonArray);
    }

    private static JsonObject stopJob(Request request, Response response) {
        // 设置响应类型为JSON
        response.type("application/json");
        // 解析 JSON 字符串为 JsonObject
        JsonObject jsonObject = JsonParser.parseString(request.body()).getAsJsonObject();
        long jobId = jsonObject.get("job_id").getAsLong();
        BelfEvn.getInstance().finishJob(jobId);

        JobResult result = new JobResult(SUCCESS, "成功停止Job");
        return result.toJson();
    }
}
